<?php

namespace App\Services;

use App\Models\College;
use App\Models\CollegeCanKao;
use App\Models\YikaoCollege;

class CollegeDataUpdateInsertSpiderService
{
    private $batchSize = 20; // 每次处理的院校数量
    private $limit = 0; // 采集数量限制，0表示无限制

    /**
     * 设置采集数量限制
     * @param int $limit 最大采集数量，0表示无限制
     */
    public function setLimit(int $limit): void
    {
        $this->limit = max(0, $limit);
    }

    /**
     * 主采集方法
     */
    public function crawlAllColleges()
    {
        echo "=== 开始采集艺考专业分数数据 ===\n";
        echo "采集限制: " . ($this->limit > 0 ? $this->limit : '无限制') . "\n";

        $page = 1;
        $collected = 0;
        while (true) {
            $colleges = YikaoCollege::query()
                ->with('yikao_college_c')
                ->skip(($page - 1) * $this->batchSize)
                ->take($this->batchSize)
                // ->where('is_yikao', 1)
                ->orderBy('id', 'asc')
                ->get();

            if (!$colleges) {
                break;
            }

            // $data = [];
            foreach ($colleges as $college) {
                try {
                    echo "[采集] 开始处理院校ID: {$college->school_id} 院校名称: {$college->name}\n";
                    $this->crawlCollegeSpecialScores($college);
                    echo "[完成] 院校ID: {$college['school_id']} 采集成功\n";
                    $collected++;
                } catch (\Exception $e) {
                    echo "[错误] 院校ID: {$college->school_id} 采集失败: " . $e->getMessage() . "\n";
                    continue;
                }
            }
            // if($data) {
            //     College::query()->insert($data);
            // }

            $page++;
            echo "[等待] 批次处理完成，等待1秒...\n";
            sleep(1); // 批次间隔
        }
        echo "=== 采集完成 ===\n";
        echo "总共采集院校数: {$collected}\n";
        if ($this->limit > 0) {
            echo "采集限制: {$this->limit}\n";
        }
    }

    /**
     * 采集单个院校的专业分数
     * @throws \Exception
     */
    private function crawlCollegeSpecialScores($college)
    {
        $collegeCan = CollegeCanKao::query()->where('college_name', $college->name)->first();
        $data = [
            'college_id' => $college->school_id * 2 + 3,
            'college_name' => $college->name,
            'introduction' => $collegeCan->introduction ?? '',
            'english_name' => $collegeCan->english_name ?? '',
            'province_id' => $college->province_id ?? '',
            'province_name' => $college->province_name ?? '',
            'city' => $college->city_name ?? '',
            'address' => $college->address ?? '',
            'official_url' => $college->yikao_college_c->school_site ?? '',
            'enroll_website' => $college->yikao_college_c->site ?? '',
            'department' => $college->belong ?? '',
            'nature' => $college->nature_name ?? '',
            'education_level' => $college->level_name ?? '',
            'create_year' => $college->create_date ?? '',
            'rank' => $college->yikao_college_c->ruanke_rank ?? 500,
            'college_phone' => $college->phone ?? '',
            'recruit_phone' => $college->phone ?? '',
            'category' => $college->yikao_college_c->type_name ?? '',
            'school_id' => $college->school_id ?? '',
        ];
        // $characteristic = [$college->level_name, $college->yikao_college_c->type_name, $college->nature_name];
        $characteristic = [];
        if($college->f985 == 1){
            $characteristic[] = 985;
        }
        if($college->f211 == 1){
            $characteristic[] = 211;
        }
        if($college->dual_class_name) {
            $characteristic[] = $college->dual_class_name;
        }
        if($college->department == 1) {
            $characteristic[] = "教育部直属";
        }
        if($college->central == 1) {
            $characteristic[] = "中央部委";
        }
        if($college->admissions == 1) {
            $characteristic[] = "强基计划";
        }
        if($college->doublehigh != 0) {
            $characteristic[] = "双高计划";
        }
        if($college->yikao_college_c->yk_feature) {
            $characteristic = array_merge($characteristic, $college->yikao_college_c->yk_feature);
        }
        $data['characteristic'] = implode(' ', $characteristic);
        $data['research_teaching'] = $collegeCan->research_teaching ?? '';
        $data['postgraduate_proportion'] = $collegeCan->postgraduate_proportion ?? '';
        $data['boys_proportion'] = $collegeCan->boys_proportion ?? '';
        $data['scholarship'] = $collegeCan->scholarship ?? '';
        $data['college_scenery'] = $collegeCan->college_scenery ? json_encode($collegeCan->college_scenery) : '';
        $data['logo_url'] = $collegeCan->logo_url ?? '';
        $data['public_address'] = $collegeCan->public_address ?? '';
        $data['canteen_dormitory'] = $collegeCan->canteen_dormitory ?? '';
        $data['college_affiliation'] = $college->belong ?? '';
        $data['employment_proportion'] = $collegeCan->employment_proportion ?? '';
       College::query()->updateOrCreate(
           ['college_name' => $college->name, 'school_id' => $college->school_id],
           $data
       );
    }
}
